﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using DBAccessLibrary;
using DBAccessLibrary.Model;
using DevExpress.Xpf.Docking;
using DevExpress.Xpf.Grid;
using QueryResource.Common;
using System.Windows;

namespace DevControlLibrary.UI
{
    /// <summary>
    /// TableDefinitionControl.xaml 的交互逻辑
    /// </summary>
    public partial class TableDefinitionControl : DockPanel
    {
        private readonly List<FieldEntity> _fieldList;
        private readonly TableEntity _table;
        private bool _isReadOnly = false;
        public TableDefinitionControl(TableEntity table)
        {
            InitializeComponent();
            this.view.InitNewRow += view_InitNewRow;
            this.gridControl1.KeyDown +=gridControl1_KeyDown;

            _table = table;
            _fieldList = new List<FieldEntity>();
            foreach (FieldEntity entity in table.FileNodes)
            {
                entity.BackUp();
                _fieldList.Add(entity);
            }
          
            this.CbType.DisplayMember = "TypeName";
            this.CbType.ValueMember = "TypeName";
            this.CbType.ItemsSource = DBOperatorFactory.GetOperator.GetTypeInfos();
            this.gridControl1.ItemsSource = new BindingList<FieldEntity>(_fieldList);

            if (SysCache.DBConnection.ConnectType == DBType.ODBC ||
                SysCache.DBConnection.ConnectType == DBType.MongoDB ||
                SysCache.DBConnection.ConnectType == DBType.Ole)
            {
                this.view.NewItemRowPosition = NewItemRowPosition.None;
                _isReadOnly = true;
                foreach (var column in this.gridControl1.Columns)
                {
                    column.AllowEditing = DevExpress.Utils.DefaultBoolean.False;
                }
            }
            
        }

        void view_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            FieldEntity entity = this.gridControl1.GetRow(e.RowHandle) as FieldEntity;

            if (_fieldList != null)
            {
                if (entity != null)
                    entity.TableName = _fieldList[0].TableName;
            }
            entity.Status = EditStatus.Add;
            entity.BackUp();
            SetEditStaus();
        }

        private void SetEditStaus()
        {
            DocumentPanel dp = this.Tag as DocumentPanel;
            if (dp == null)
                return;
            if (this._fieldList.Count(o => o.Status != EditStatus.UnChange) > 0)
            {
                if (dp.Caption.ToString().IndexOf('*') < 0)
                {
                    dp.Caption += "*";
                }
            }
            else
            {
                int index =dp.Caption.ToString().IndexOf('*');
                if (index > 0)
                {
                    dp.Caption = dp.Caption.ToString().Remove(index);
                }
            }
        }

        public Action<string, Color> WriteLog { get; set; }

        public void RollBack()
        {
            _table.RollBack();
        }
        public bool Save()
        {
            BindingList<FieldEntity> newList = this.gridControl1.ItemsSource as BindingList<FieldEntity>;
            if (newList == null)
                return false;
            try
            {

                DBOperatorFactory.GetGrammar(SysCache.DBConnection).SaveChange(_table, newList, WriteLog, msg =>
                {
                    return MessageBoxHelper.ShowMessage(msg, "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK;
                });
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                SetEditStaus();
                this.gridControl1.RefreshData();
            }
        }

        private void view_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (e.RowHandle == DataControlBase.NewItemRowHandle)
                return;
           if(!e.OldValue.Equals(e.Value))
           {
               SetEditStaus();
           }
        }

        private void gridControl1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (this.view.FocusedRowHandle == DataControlBase.NewItemRowHandle)
                return;
            if (_isReadOnly)
                return;
            if (e.Key == System.Windows.Input.Key.Delete)
            {

                FieldEntity entity = this.gridControl1.GetRow(this.view.FocusedRowHandle) as FieldEntity;
                if (entity != null)
                {
                    if (MessageBoxHelper.ShowMessage("是否确定要删除此列", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                    {
                        try
                        {
                            entity.Status = EditStatus.Delete;
                            SetEditStaus();
                            this.gridControl1.RefreshRow(this.view.FocusedRowHandle);

                        }
                        catch (Exception ex)
                        {
                            WriteLog(ex.Message, Colors.Red);
                        }
                    }
                }
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (_isReadOnly)
            {
                MessageBoxHelper.Show("该数据库不支持修改");
                return;
            }
            if (this.view.SelectedRows.Count > 0)
            {
                List<string> parmaryKey = (from FieldEntity row in this.view.SelectedRows
                                           select row.Name).ToList();
                BindingList<FieldEntity> newList = this.gridControl1.ItemsSource as BindingList<FieldEntity>;
                foreach (FieldEntity entity in newList)
                {
                    entity.IsPrimaryKey = parmaryKey.Contains(entity.Name);
                }
                SetEditStaus();
            }
            else
            {
                MessageBoxHelper.Show("请选择一行记录");
            }
        }
    }
   
}
